package com.itheima;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitUtils {
    //连接对象
    private static Connection connection=null;
    //频道（通道）
    private static Channel channel=null;
    static{
        try {
            //初始化连接
            init();
            // 虚拟机退出时关闭
            Runtime.getRuntime().addShutdownHook(new Thread(){
                @Override
                public void run() {
                    System.out.println("--------释放关闭资源中....");
                    //关闭释放资源
                    destory();
                    System.out.println("--------释放关闭资源成功....");
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //初始化
    public static void init() throws Exception {
        //创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置连接参数 - 主机地址;默认为 localhost
        connectionFactory.setHost("localhost");
        //设置连接参数 - 连接端口;默认为 5672
        connectionFactory.setPort(5672);
        //设置连接参数 - 虚拟主机名称;默认为 /
        connectionFactory.setVirtualHost("/itcast");
        //设置连接参数 - 连接用户名；默认为guest
        connectionFactory.setUsername("mrchen");
        //设置连接参数 - 连接密码；默认为guest
        connectionFactory.setPassword("mrchen");
        //创建连接
        connection = connectionFactory.newConnection();
        //创建频道
        channel = connection.createChannel();
    }

    //释放资源
    public static void destory(){
        //关闭频道
        if(null !=channel && channel.isOpen()){
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        }

        //关闭连接
        if(null !=connection && connection.isOpen()){
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    //获取连接
    public static Connection getConnection(){
        return connection;
    }

    //获取连接
    public static Channel getChannel(){
        return channel;
    }
}